package com.sneakxy.mybatis.commons.repository.query;

import java.util.ArrayList;
import java.util.Map;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;
import org.springframework.data.domain.Pageable;

import com.sneakxy.mybatis.commons.dialect.Dialect;
import com.sneakxy.mybatis.commons.utils.MybatisUtils;

/**
 * @author 潜行的青衣
 */
public class MybatisPageBoundSql extends BoundSql {

	private BoundSql boundSql;
	
	private Dialect dialect;
	
	private Pageable page;
	
	private String sql;
	
	/**
	 * @param configuration
	 * @param boundSql
	 * @param page
	 * @param dialect
	 */
	public MybatisPageBoundSql(Configuration configuration, BoundSql boundSql, Pageable page, Dialect dialect) {
		super(configuration, null, new ArrayList<ParameterMapping>(), null);
		this.boundSql = boundSql;
		this.dialect = dialect;
		this.page = page;
		this.init();
	}
	
	@SuppressWarnings("unchecked")
	private void init() {
		this.sql = new StringBuilder()
				.append(boundSql.getSql())
				.append(MybatisUtils.buildSortSql(page.getSort(), getDialect())).toString();
		this.getParameterMappings().addAll(this.boundSql.getParameterMappings());
		this.sql = this.dialect.process(this.sql, (Map<String, Object>) this.getParameterObject(), page, this.getParameterMappings());
	}
	
	
	@Override
	public String getSql() {
		return this.sql;
	}
	
	@Override
	public Object getParameterObject() {
		return boundSql.getParameterObject();
	}
	
	@Override
	public boolean hasAdditionalParameter(String name) {
		return boundSql.hasAdditionalParameter(name);
	}
	
	@Override
	public void setAdditionalParameter(String name, Object value) {
		boundSql.setAdditionalParameter(name, value);
	}
	
	@Override
	public Object getAdditionalParameter(String name) {
		return boundSql.getAdditionalParameter(name);
	}

	public Dialect getDialect() {
		return dialect;
	}

}
